package com.unience.ec2.eclipse.config.account;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class AccountManager {
	
	private List<Account> accountList;
	
	public static final String ACCOUNTS_DIR = "accounts";
	private static final String NAME = "name";
	private static final String KEY = "key";
	private static final String SECRET = "secret";
	private static final String OWNERID = "ownerid";
	
	public AccountManager(){
		super();
		
		load();
	}
	
	private void load(){
		
		accountList = new ArrayList<Account>();
		
		File dirAccounts = new File(ACCOUNTS_DIR);
		
		if (!dirAccounts.exists()){
			boolean success = dirAccounts.mkdir();
		}
		
		System.out.println("Dir Accounts: " + dirAccounts.getAbsolutePath());
		
		FilenameFilter filter = new FilenameFilter() {
	        public boolean accept(File dir, String name) {
	        	if (name.endsWith(".properties")){
	        		return true;
	        	}else{
	        		return false;
	        	}
	        }
	    };
	        
	    
	    // The list of files can also be retrieved as File objects
	    File[] files = dirAccounts.listFiles(filter);
	    
	    for (File file : files) {
			Properties properties = new Properties();
			
			try {
				properties.load(new FileInputStream(file));
				Account account = new Account();
				
				account.setName((String)properties.getProperty(NAME));;
				account.setKey((String)properties.getProperty(KEY));;
				account.setSecret((String)properties.getProperty(SECRET));;
				account.setOwnerId((String)properties.getProperty(OWNERID));;
				
				
				accountList.add(account);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	
		}

		
	}

	public List<Account> getAccountList() {
		return accountList;
	}

	public void setAccountList(List<Account> accountList) {
		this.accountList = accountList;
	}
	
	
	public Account getAccount(){
		Account ret = null;
		
		
		
		return ret;
	}
	
	public void addAccount(Account account){
		
		Properties properties = new Properties();
		
		properties.setProperty(NAME, account.getName());
		properties.setProperty(KEY, account.getKey());
		properties.setProperty(SECRET, account.getSecret());
		properties.setProperty(OWNERID, account.getOwnerId());
		
		File newAccount = new File(ACCOUNTS_DIR + "/" + account.getName() +".properties");
		
		if (!newAccount.exists()){
			try {
				boolean success = newAccount.createNewFile();
				if (success) {

					properties.store(new FileOutputStream(newAccount), "");

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		accountList.add(account);
		
		
		
		
		
	}

}
